﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

using SBPweb.RIA.Client.Controls.Base;
using SBPweb.RIA.Client.Controls.Controllers;
using SBPweb.RIA.Client.Controls.Windows;

using SBPweb.PROvibe.Client.Core.Controllers;
using SBPweb.PROvibe.Client.Core.Controls;

using SBPweb.PROvibe.Client.Library.Base;


namespace SBPweb.PROvibe.Client.Presenter
{

    public partial class App : ExtendableApplication
    {

        #region Fields

        private ErrorWindow errorWindow;

        #endregion

        #region Constructor logic

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            IsSettingsPersistencyEnabled = true;
        }

        #endregion

        #region Event handlers

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (this.IsRunningOutOfBrowser)
            {
                if (Application.Current.HasElevatedPermissions)
                {
                    Application.Current.MainWindow.WindowState = WindowState.Maximized;
                }

                CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Application_CheckAndDownloadUpdateCompleted);
                CheckAndDownloadUpdateAsync();
            }
            else
            {
                InitParams = new InitialParameters(e.InitParams, false);
                Application_InitializeRootVisual();
            }
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                ShowErrorDialog(e);
            });
            e.Handled = true;
            //// If the app is running outside of the debugger then report the exception using
            //// the browser's exception mechanism. On IE this will display it a yellow alert 
            //// icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {
            //    // NOTE: This will allow the application to continue running after an exception has been thrown
            //    // but not handled. 
            //    // For production applications this error handling should be replaced with something that will 
            //    // report the error to the website and stop the application.
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void Application_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                Application_InitializeRootVisual(false);
                RootVisual = new Desktop();
                MessageWindow msg = new MessageWindow("SecondaryRootPanel");
                msg.ChromeBrush = new SolidColorBrush(Color.FromArgb(208, 255, 255, 255));
                msg.Margin = new Thickness(5);
                msg.MinWidth = 300;
                msg.MinHeight = 200;
                msg.Title = "Új verzió frissítése...";
                msg.Header = "Új verzió érhető el az alkalmazásból!";
                TextBlock tb = new TextBlock();
                tb.Text = "A verzió frissítéséhez be kell zárnia, majd újra kell indítania a programot!\n\nA bezáráshoz kattintson az Ok gombra...";
                tb.TextWrapping = TextWrapping.Wrap;
                msg.Body = tb;
                msg.HasCloseButton = false;
                msg.HasOkButton = true;
                msg.OpenDialog();
                msg.Closed += new EventHandler(Application_CheckAndDownloadUpdatedAndClosing);
            }
            else
            {
                Application_InitializeRootVisual();
            }
        }

        private void Application_CheckAndDownloadUpdatedAndClosing(object sender, EventArgs e)
        {
            Application.Current.MainWindow.Close();
        }

        private void Application_InitializeRootVisual()
        {
            Application_InitializeRootVisual(true);
        }

        private void Application_InitializeRootVisual(bool instantiateRootVisual)
        {
            InitialParameters initDict = InitParams as InitialParameters;
            if (initDict == null)
            {
                InitParams = initDict = new InitialParameters();
            }

            PackageLoaderController.RegisterApplicationSingleton();
            NavigationController.RegisterApplicationSingleton();

            CoreControllers.RegisterApplicationSingletons();

            if (instantiateRootVisual)
            {
                RootVisual = new PageManager();
                NavigationController.Controller.NavigateToRootPage();
            }
        }

        private void ShowErrorDialog(ApplicationUnhandledExceptionEventArgs e)
        {
            if (errorWindow == null)
            {
                errorWindow = new ErrorWindow("WindowsRootPanel", e.ExceptionObject);
            }
            else
            {
                errorWindow.SetUIContentBasedOnException(e.ExceptionObject);
            }
            errorWindow.OpenDialog();
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }

        #endregion

    }

}